{% extends "base.html" %}
{% block title %}{{title}} - Coupons Management{% endblock %}
{% block deals %}
<!--CSS file (default YUI Sam Skin) -->
<link type="text/css" rel="stylesheet"
      href="http://yui.yahooapis.com/2.7.0/build/datatable/assets/skins/sam/datatable.css">
<link rel="stylesheet" type="text/css"
      href="http://yui.yahooapis.com/2.7.0/build/paginator/assets/skins/sam/paginator.css"/>
<!-- Dependencies -->
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/element/element-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/datasource/datasource-min.js"></script>
<!-- OPTIONAL: JSON Utility (for DataSource) -->
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/json/json-min.js"></script>
<!-- OPTIONAL: Connection Manager (enables XHR for DataSource) -->
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/connection/connection-min.js"></script>
<!-- OPTIONAL: Drag Drop (enables resizeable or reorderable columns) -->
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/dragdrop/dragdrop-min.js"></script>
<!-- Source files -->
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/datatable/datatable-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/paginator/paginator-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/button/button-min.js"></script>
<style type="text/css">
    .align_center {
        text-align: center !important;
    }
    .nowrap{
        white-space:nowrap;
    }
    .content_div{
        font-size:0.9em;
        margin:2px;
    }
    .title{
        font-size:1.1em;
        font-weight:bold;
    }
</style>
<script type="text/javascript">
    YAHOO.util.Event.addListener(window, "load", function() {
        YAHOO.coupons.DynamicData = function() {
            var detailLinkFormatter = function(elCell, oRecord, oColumn,oData) {
                elCell.innerHTML = '<img src="'+oRecord.getData()['image']+'" border="0" align="right"/>'+
                                   '<div><ul><li><label>Code:</label><span class=title>' + oRecord.getData()['code'] + '</span></li>' +
                                   "<li><label>Discount:</label><span class=content_div>"+oRecord.getData()['discount']+ '</span></li>'+
                                   '<li><label>Site:</label><a href="'+oRecord.getData()['site_url']+'" target=_blank>'+
                                    oRecord.getData()['site_name']+'</a></li></ul></div>';
            };
            // Column definitions
            var myColumnDefs = [ // sortable:true enables sorting
                {key:"check",resizeable:true,label:"",formatter:YAHOO.widget.DataTable.formatCheckbox,className:"align_center"},
                {key:"code", label:"Code Info", formatter:detailLinkFormatter,sortable:true},
                {key:"created_date", label:"Created Date", sortable:true,formatter:"date",className:"nowrap"},
                {key:"key",resizeable:true,label:"Edit",formatter:function(elCell, oRecord, oColumn, oData){
                    elCell.innerHTML = "<a href='/coupon/"+oData+"'>Edit</a>";
                }}
            ];

            var buildQueryString = function (state, dt) {
                return "?arg0=" + state.pagination.recordOffset +
                       "&arg1=" + state.pagination.rowsPerPage + '&time=' + new Date().getTime();
            };

            // DataSource instance
            var myDataSource = new YAHOO.util.DataSource("/json/getCoupons");
            myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
            myDataSource.responseSchema = {
                resultsList: "records",
                fields: [
                    {key:"code"},
                    {key:"created_date"},
                    {key:"key"},
                    {key:"discount"},
                    {key:"site_url"},
                    {key:"site_name"},
                    {key:"image"}
                ],
                metaFields: {
                    totalRecords: "totalRecords" // Access to value in the server response
                }
            };

            var myPaginator = new YAHOO.widget.Paginator({
                containers : ['paging_nav_0','paging_nav_1'],
                rowsPerPage : 30,
                rowsPerPageOptions : [30,60,100],
                template : "{PreviousPageLink} <strong>{CurrentPageReport}</strong> {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
            });

            // DataTable configuration
            var myConfigs = {
                initialRequest: "?arg0=0&arg1=30&time=" + new Date().getTime(),  //'startIndex=0&results=25'
                generateRequest: buildQueryString,
                dynamicData: true, // Enables dynamic server-driven data
                sortedBy : {key:"created_date", dir:YAHOO.widget.DataTable.CLASS_DESC}, // Sets UI initial sort arrow
                paginator: myPaginator // Enables pagination
            };

            // DataTable instance
            var myDataTable = new YAHOO.widget.DataTable("coupons_container", myColumnDefs, myDataSource, myConfigs);
            // Update totalRecords on the fly with value from server
            myDataTable.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
                oPayload.totalRecords = oResponse.meta.totalRecords;
                return oPayload;
            };

            // Selects any cell that receives a checkbox click
            myDataTable.subscribe("checkboxClickEvent", function(oArgs) {
                var elCheckbox = oArgs.target;
                var elRow = this.getTrEl(elCheckbox);
                if (elCheckbox.checked) {
                    this.selectRow(elRow);
                } else {
                    this.unselectRow(elRow);
                }
            });

            myDataTable.subscribe("cellClickEvent", myDataTable.onEventShowCellEditor);

            var selectedCouponIds = function(recordSet,selectedRows) {
                var coupon_keys  = "coupon_keys=";
                for (var x = 0, length=selectedRows.length; x < length; x++) {
                    var record =  recordSet.getRecord(selectedRows[x]);
                    coupon_keys += record.getData().key;
                    if(x < length-1){
                        coupon_keys+=",";
                    }
                }
                return coupon_keys;
            };
            var deleteCoupons = function() {
                var selected = myDataTable.getSelectedRows();
                var rset = myDataTable.getRecordSet();
                if (selected.length > 0) {
                    YAHOO.util.Connect.asyncRequest('POST', '/json/deleteCoupons',
                    {
                        success: function (o) {
                            if (o.responseText == 'true') {
                                for (var x = 0; x < selected.length; x++) {
                                    myDataTable.deleteRow(rset.getRecordIndex(rset.getRecord(selected[x])));
                                }
                            } else {
                                alert(o.responseText);
                            }
                        },
                        failure: function (o) {
                            alert(o.statusText);
                        },
                        scope:this
                    }, selectedCouponIds(rset, selected)
                            );
                } else {
                    alert("Please select at least one Coupon to delete.");
                }
            };

            YAHOO.util.Event.addListener("deleteCoupon", "click", deleteCoupons);

            return {
                ds: myDataSource,
                dt: myDataTable
            };

        }();
    });
</script>
<div>
    <div style="padding-bottom:3px">
        {% if user_is_admin %}
        <button id="deleteCoupon">Delete</button>
        {% endif %}
    </div>
    <div id="paging_nav_0"> </div>
    <div id="coupons_container" width="100%">
    </div>
    <div id="paging_nav_1"> </div>
</div>
{% endblock %}

